package com.atguigu.tingshu.payment.context;

import com.atguigu.tingshu.payment.strategy.PaymentStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class PaymentStrategyContext implements ApplicationContextAware {

    // 定义一个Map，存储PaymentStrategy接口的实现类对象
    private static final Map<String , PaymentStrategy> PAYMENT_STRATEGY_MAP = new ConcurrentHashMap<>() ;

    public static PaymentStrategy getPaymentStrategy(String paymentType) {
        return PAYMENT_STRATEGY_MAP.get(paymentType) ;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        applicationContext.getBeansOfType(PaymentStrategy.class).values()
                .forEach(paymentStrategy -> {
                    String paymentType = paymentStrategy.getPaymentType();
                    PAYMENT_STRATEGY_MAP.put(paymentType , paymentStrategy) ;
                });
    }
}
